import { Effect, Reducer, Subscription, useHistory } from 'umi';
import { getlogin, get_Authority, get_UserInfo } from '@/services/login'
import { setCookies, getCookies } from '@/utils/cook'
import { menulist } from '@/utils/menu'
import { Idifflist, Iuseinfo, use } from '@/interface/login'

let hasInfo: boolean = false
export interface IndexModelState {
  isLogin: boolean
  hasInfo: boolean
  difflist: Idifflist[]
  useinfo: use
  name: string
}

export interface IndexModelType {
  namespace: 'login';
  state: IndexModelState;
  effects: {
    login: Effect,
    getAuthority: Effect,
    getUserInfo: Effect
  };
  reducers: {
    save: Reducer<IndexModelState>;
    // 启用 immer 之后
    // save: ImmerReducer<IndexModelState>;
  };
  subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
  namespace: 'login',  //命名空间  

  state: {
    name: '',
    isLogin: false,
    hasInfo: false,
    difflist: [],        //对比后的展示目录
    useinfo: {            //用户信息
      avatar: "",
      iat: 1615353315,
      identity_id: "63no9p-8y0k4",
      identity_text: "管理员",
      signTime: 1615353315269,
      user_id: "w6l6n-cbvl6s",
      user_name: "chenmanjie",
    }
  },

  effects: {    //处理异步方法  用...函数
    //登录
    *login({ payload }, { call, put }) {
      let logininfo = yield call(getlogin, payload)
      if (logininfo.code === 1) {
        //登录成功  保存cookie
        setCookies("token", logininfo.token)
        yield put({
          type: "save",
          payload: { isLogin: true }
        })
      }
    },

    //根据用户id获取权限视图
    *getAuthority({ payload }, { call, put }) {
      let result = yield call(get_Authority, payload)
      if (result.code == 1) {
        let list: Idifflist[] = []
        menulist.map(item => {
          let children = item.children.filter(v => {
            return result.data.findIndex((value: Iuseinfo) => value.view_id == v.meta.view_id) != -1
          })
          list.push({ ...item, children })
        })
        yield put({
          type: "save",
          payload: { difflist: list }
        })
      }

    },

    //获取用户信息
    *getUserInfo({ payload }, { call, put }) {
      let result = yield call(get_UserInfo)
      console.log(result, "用户信息")
      if (result.code === 1) {
        hasInfo = true
        yield put({
          type: "save",
          payload: { useinfo: result.data }
        })

        yield put({
          type: 'getAuthority',
          payload: { user_id: result.data.user_id }
        })
        yield put({
          type: 'save',
          payload: { name: result.data.user_name }
        })
      }

    }
  },
  reducers: {
    save(state, action) {        //reduce  来改变state

      return {
        ...state,
        ...action.payload,
      };
    },
  },


  subscriptions: {                            //监听路由的
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {

        //判断是否登录
        let token = getCookies('token')
        if (token) {
          //代表登录了   1.跳转到指定页面   2.获取用户信息  3.获取视图权限
          if (pathname == "/login") {
            history.replace("/main")
          }
          // if (!hasInfo) {       //没有获取用户信息就获取一次  防止多次请求(获取)
          dispatch({
            type: "getUserInfo"
          })
          // }


        } else {
          //没有登录   调回登录页      encodeURIComponent(路径)  吧url地址进行编码
          if (pathname !== '/login') {
            history.replace(`/login?redirect=${encodeURIComponent(pathname)}`)
            dispatch({
              type: "save",
              payload: { isLogin: false }
            })
          }

        }


      });
    }
  }
};
export default IndexModel;
